<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <sticky :z-index="10" :class-name="'sub-navbar '+postForm.status">
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          保存
        </el-button>
        <el-button v-loading="loading" type="warning" @click="cancle">
          取消
        </el-button>
      </sticky>

      <div class="createPost-main-container">

        <el-row>
          <el-col :span="24">

            <div class="postInfo-container">
              <el-row>
                <el-form-item style="margin-bottom: 30px;" prop="title">
                  标题
                  <el-input v-model="postForm.title" style="width: 350px"/>
                </el-form-item>

                <el-form-item style="margin-bottom: 30px;" prop="description">
                  价钱
                  <el-input v-model="postForm.price" style="width: 350px"/>
                </el-form-item>

                <el-form-item style="margin-bottom: 30px;" prop="stock">
                  库存
                  <el-input v-model="postForm.stock" style="width: 350px"/>
                </el-form-item>


              </el-row>
            </div>
          </el-col>
        </el-row>
        图片
        <el-form-item prop="imgUrl" style="margin-bottom: 30px;">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8280/file"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="postForm.imgUrl" :src="postForm.imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>

          <div v-for="(item,i) in saleAttr">
            <p>{{item.baseSaleAttrKeyName}}</p>
            <!--            <div v-for="(iitem,j) in item.saleAttrValues">-->
            <!--              <p>{{iitem.saleAttrValueName}}</p>-->
            <!--            </div>-->

            <el-select v-model="saleAttrValue[i]" placeholder="请选择" style="width: 110px" class="filter-item"
                       @change="changeSelect($event,item,i)">
              <el-option v-for="iitem in item.saleAttrValues" :key="iitem.id" :label="iitem.saleAttrValueName"
                         :value="iitem.id"/>
            </el-select>
          </div>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
  import Tinymce from '@/components/Tinymce'
  import Sticky from '@/components/Sticky' // 粘性header组件
  import {saveSku, getSku} from '@/api/sku'
  import {getSaleAttr} from "../../../api/attributes";

  const defaultForm = {
    title: '',
    price: '',
    productId: undefined,
    imgUrl: '',
    spuId: undefined,
    skuSaleAttrList: []
  }

  export default {
    name: 'SkuDetail',
    components: {Tinymce, Sticky},
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      const validateRequire = (rule, value, callback) => {
        if (value === '') {
          this.$message({
            message: rule.field + '为必传项',
            type: 'error'
          })
          callback(new Error(rule.field + '为必传项'))
        } else {
          callback()
        }
      }
      return {
        spuId: null,
        saleAttrValue: [],
        saleAttr: [],
        postForm: Object.assign({}, defaultForm),
        loading: false,
        imgUrl: '',
        userListOptions: [],
        rules: {
          // imgUrl: [{ validator: validateRequire }],
          title: [{validator: validateRequire}]
        },
        tempRoute: {}
      }
    },
    computed: {},
    created() {
      this.spuId = this.$route.query.spuId
      this.fetchSaleAttr(this.spuId);

      if (this.isEdit) {
        //编辑
        console.log("编辑:", this.$route.params.id)
        const skuId = this.$route.params && this.$route.params.id
        console.log("skuId", skuId)
        this.fetchData(skuId)
      } else {
        //新增
        this.postForm = Object.assign({}, defaultForm)
      }

      // Why need to make a copy of this.$route here?
      // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
      // https://github.com/PanJiaChen/vue-element-admin/issues/1221
      this.tempRoute = Object.assign({}, this.$route)
    },
    methods: {
      handleAvatarSuccess(e) {
        console.log('成功', e)
        this.imgUrl = e.data.url
        this.postForm.imgUrl = e.data.url
      },
      fetchData(id) {
        getSku(id).then(r1 => {
          console.log("sku数据", r1.data)
          this.postForm = r1.data
          //处理销售属性
          let selectedSaleAttrValueName = [];
          for (var i = 0; i < this.postForm.skuSaleAttrList.length; i++) {
            selectedSaleAttrValueName.push(this.postForm.skuSaleAttrList[i].saleAttrValueName)
          }
          this.saleAttrValue = selectedSaleAttrValueName

          this.setTagsViewTitle()

          this.setPageTitle()
        }).catch(err => {
          console.log(err)
        })
      },
      setTagsViewTitle() {
        const title = '编辑Sku'
        const route = Object.assign({}, this.tempRoute, {title: `${title}-${this.postForm.id}`})
        this.$store.dispatch('tagsView/updateVisitedView', route)
      },
      setPageTitle() {
        const title = '编辑Sku'
        document.title = `${title} - ${this.postForm.id}`
      },
      submitForm() {
        this.postForm.productId = this.spuId
        console.log(this.postForm)
        this.$refs.postForm.validate(valid => {
          if (valid) {
            this.loading = true

            saveSku(this.postForm).then(r1 => {
              this.loading = false
              this.$notify({
                title: '成功',
                message: '发布成功',
                type: 'success',
                duration: 2000
              })
              this.$store.dispatch('tagsView/delView', this.$route).then(() => {
                this.$nextTick(() => {
                  this.$router.replace({
                    path: '/sku/list/' + this.spuId
                  })
                })
              })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      cancle() {
        if (this.postForm.detail.length === 0 || this.postForm.title.length === 0) {
          this.$message({
            message: '请填写必要的标题和内容',
            type: 'warning'
          })
          return
        }
        this.$message({
          message: '保存成功',
          type: 'success',
          showClose: true,
          duration: 1000
        })
      },
      fetchSaleAttr(spuId) {
        getSaleAttr(spuId).then(r1 => {
          this.saleAttr = r1.data
        })
      },
      changeSelect(value, item, i) {
        let selectedSaleAttrValue = item.saleAttrValues.find((iitem) => {
          return iitem.id === value;
        });

        if (this.isEdit) {
          console.log("postForm:", this.postForm)
          console.log("选择：", value, item, i)
          this.postForm.skuSaleAttrList[i].saleAttrKeyId = item.id
          this.postForm.skuSaleAttrList[i].saleAttrValueId = value
          this.postForm.skuSaleAttrList[i].saleAttrKeyName = item.baseSaleAttrKeyName
          this.postForm.skuSaleAttrList[i].saleAttrValueName = selectedSaleAttrValue.saleAttrValueName
          console.log("postForm:", this.postForm)
        }else{
          this.postForm.skuSaleAttrList[i] = {
            saleAttrKeyId : item.id,
            saleAttrValueId : value,
            saleAttrKeyName : item.baseSaleAttrKeyName,
            saleAttrValueName : selectedSaleAttrValue.saleAttrValueName

          }
        }
      }

    }
  }
</script>

<style lang="scss" scoped>
  @import "~@/styles/mixin.scss";

  .createPost-container {
    position: relative;

    .createPost-main-container {
      padding: 40px 45px 20px 50px;

      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;

        .postInfo-container-item {
          float: left;
        }
      }
    }

    .word-counter {
      width: 40px;
      position: absolute;
      right: 10px;
      top: 0px;
    }
  }

  .news-textarea /deep/ {
    textarea {
      padding-right: 40px;
      resize: none;
      border: none;
      border-radius: 0px;
      border-bottom: 1px solid #bfcbd9;
    }
  }

  /*图片*/
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    border: 1px solid #d9d9d9;
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    border: 1px solid #d9d9d9;
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

